package com.katesoft.scale4j.rttp.mocks;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ILock;
import com.hazelcast.core.LifecycleService;
import com.katesoft.scale4j.rttp.hibernate.SpringHazelcastBridge;
import org.junit.Ignore;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/** @author kate2007 */
@Ignore
public class SpringHazelcastBridgeMock extends SpringHazelcastBridge
{
    private Map<String, AtomicBoolean> booleanMap = new HashMap<String, AtomicBoolean>();
    private Map<String, ILock> lockMap = new HashMap<String, ILock>();

    @Override
    public HazelcastInstance getHazelcastInstance()
    {
        HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class);
        LifecycleService lifecycleService = mock(LifecycleService.class);
        when(lifecycleService.isRunning()).thenReturn(true);
        when(lifecycleService.pause()).thenReturn(true);
        when(lifecycleService.resume()).thenReturn(true);
        when(hazelcastInstance.getLifecycleService()).thenReturn(lifecycleService);
        when(hazelcastInstance.getLock(anyString())).thenAnswer(new Answer<Object>()
        {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable
            {
                String name = (String) invocation.getArguments()[0];
                if (lockMap.containsKey(name)) { return lockMap.get(name); }
                ILock iLock = mock(ILock.class);
                when(iLock.tryLock()).thenReturn(true);
                lockMap.put(name, iLock);
                return iLock;
            }
        });
        return hazelcastInstance;
    }

    @Override
    public AtomicBoolean getAtomicBoolean(String name)
    {
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        booleanMap.put(name, atomicBoolean);
        return atomicBoolean;
    }

    @Override
    public void updateAtomicBoolean(String name,
                                    boolean newValue)
    {
        AtomicBoolean atomicBoolean = booleanMap.get(name);
        atomicBoolean.set(newValue);
    }
}
